from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import Node
from mininet.log import setLogLevel, info
from mininet.cli import CLI

from jinja2 import Environment, FileSystemLoader, PackageLoader, select_autoescape


class Router(Node):
    def config(self, **params):
        super(Router, self).config(**params)
        # Enable forwarding on the router
        self.cmd('sysctl net.ipv4.ip_forward=1')
        

    def terminate(self):
        self.cmd('sysctl net.ipv4.ip_forward=0')
        self.cmd('sudo pkill openr')
        self.cmd('sudo pkill ddm')
        super(Router, self).terminate()

class Mycli(CLI, object):
    def __init__(self, net):
        super(Mycli, self).__init__(net)

    def do_start_openr(self, line):
        for node in self.mn.topo.nodes():
            if 'h' in node:
                continue
            self.mn.get(node).cmd('nohup /home/vagrant/fbsource/build/openr/openr_bin --config test/%s.conf > log/%s.openr.log 2>&1 &' % (node, node))

    def do_start_ddm(self, line):
        for node in self.mn.topo.nodes():
            if 'h' in node:
                continue
            self.mn.get(node).cmd('nohup /home/vagrant/fbsource/build/ddm/ddm_bin --node_name %s > log/%s.ddm.log 2>&1 &' % (node, node))


class MyTopo(Topo):
    def build(self, *args, **params):
        A = self.addNode('A', cls=Router, ip=None, privateDirs=['/tmp'])
        B = self.addNode('B', cls=Router, ip=None, privateDirs=['/tmp'])
        C = self.addNode('C', cls=Router, ip=None, privateDirs=['/tmp'])
        D = self.addNode('D', cls=Router, ip=None, privateDirs=['/tmp'])
        
        self.addLink(A, B, params1={
                     'ip': '10.1.0.0/31'}, params2={'ip': '10.1.0.1/31'})
        self.addLink(A, C, params1={
                     'ip': '10.2.0.0/31'}, params2={'ip': '10.2.0.1/31'})
        self.addLink(B, D, params1={
                     'ip': '10.3.0.0/31'}, params2={'ip': '10.3.0.1/31'})
        self.addLink(C, D, params1={
                     'ip': '10.4.0.0/31'}, params2={'ip': '10.4.0.1/31'})


topo = MyTopo()
net = Mininet(topo=topo, controller=None)
net.start()
Mycli(net)
net.stop()